package com.ustcinfo.study.hive.r2.yangyang;


import java.sql.*;

/**
 * Describe:  hive连接，并执行HiveSql
 * Author: yang.yang
 * Mail: yang.yang2@ustcinfo.com
 * Date: 2018年08月03日 20:03
 */
public class HiveTest {



    // hive链接地址
    private static String url = "jdbc:hive2://nodex3:10000/default";

    //hive用户名
    private static String userName = "root";

    // hive密码
    private static String pwd = "";

    // hive 驱动
    private static String driver = "org.apache.hive.jdbc.HiveDriver";

    private static Connection connection = null;
    private static Statement statement = null;
    private static ResultSet resultSet = null;

    // 查询tables sql
    private static String showTableSql = "show tables";

    // 创建内部表dns_yangyang sql
    private static String createSql = "create table dns_yangyang(ip string,domain_name string,access_time string,target_ip string,status string)row format delimited fields terminated by '#' ";
    // 加载数据到dns_yangyang sql
    private static String localDataSql = "load data local inpath '/home/dnsSample' into table dns_yangyang ";

    // 统计出dns_yangyang表中域名个数
    private static String countSql = "select domain_name,count(*) from dns_yangyang group by domain_name";
    //删除dns_yangyang表
    private static  String deletSql="drop table dns_yangyang";



    public static void main(String[] args) throws SQLException {

        //  加载hive驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            System.out.println("驱动加载失败");
            e.printStackTrace();
        }
        try {
            // 连接hive
            connection = DriverManager.getConnection(url, userName, pwd);
            if (connection != null) {
                System.out.println("hive 连接成功");
            } else {
                System.out.println("hive 连接失败");
            }
            statement = connection.createStatement();

            // 获取数据库中所有的表,查询要创建的表，存在就删除
            resultSet = statement.executeQuery(showTableSql);
            while (resultSet.next()) {
                if (resultSet.getString(1).equals("dns_yangyang")){
                    statement.execute(deletSql);
                    break;
                }
                System.out.println(resultSet.getString(1));
            }
            statement.execute(createSql);
            statement.execute(localDataSql);
            //获得统计结果，打印输出
            resultSet = statement.executeQuery(countSql);
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1) + "\t" + resultSet.getInt(2));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        }


    }}
